package com.rchat.pocmini.greendao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.rchat.pocmini.greendao.dao.DaoMaster;
import com.rchat.pocmini.greendao.dao.DaoSession;

/**
 * Created by ljd on 2017/4/10.
 */

public class DBManager {
    //是否加密
    public static final boolean ENCRYPTED = true;

    private static final String DB_NAME = "rchat_db";
    private static DBManager mDBManager = null;
    private DaoMaster.DevOpenHelper mDevOpenHelper;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;


    public DBManager(Context context) {
        //初始化数据库信息
        if (mDBManager == null) {
            mDevOpenHelper = new
                    DaoMaster.DevOpenHelper(context, DB_NAME);
            mDaoMaster = new DaoMaster(mDevOpenHelper.getWritableDatabase());
            mDaoSession = mDaoMaster.newSession();
        }

    }

    public static DBManager getInstance(Context context) {
        if (null == mDBManager) {
            synchronized (DBManager.class) {
                if (null == mDBManager) {
                    mDBManager = new DBManager(context);
                }
            }
        }
        return mDBManager;
    }

    public SQLiteDatabase getReadableDatabase(Context context) {
        if (null == mDevOpenHelper) {
            getInstance(context);
        }
        return mDevOpenHelper.getReadableDatabase();
    }

    public SQLiteDatabase getWritableDatabase(Context context) {
        if (null == mDevOpenHelper) {
            getInstance(context);
        }
        return mDevOpenHelper.getWritableDatabase();
    }

    public DaoMaster getDaoMaster(Context context) {
        if (null == mDaoMaster) {
            synchronized (DBManager.class) {
                if (null == mDaoMaster) {
                    mDaoMaster = new DaoMaster(getWritableDatabase(context));
                }
            }
        }
        return mDaoMaster;
    }

    public DaoSession getDaoSession(Context context) {
        if (null == mDaoSession) {
            synchronized (DBManager.class) {
                mDaoSession = getDaoMaster(context).newSession();
            }
        }
        return mDaoSession;
    }
}
